package org.wx.io.netty.tcp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @description: tcp 粘包和拆包 client
 * @author: wangxun
 * @createDate: 2021/2/22
 * @version: 1.0
 */
@Slf4j
public class TcpClient implements Runnable{
    private InetSocketAddress inetSocketAddress;

    public TcpClient(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }

    @Override
    public void run() {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new TcpClientInitializer());

            ChannelFuture connect = bootstrap.connect(inetSocketAddress);
            connect.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()){
                        log.info("连接到服务器成功...");
                    }
                }
            });

            connect.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        TcpClient tcpClient = new TcpClient(new InetSocketAddress("127.0.0.1", 1999));
        new Thread(tcpClient).start();
    }
}
